package de.idgard.android.addon.ui.services.impl;

import java.util.Arrays;
import java.util.Collection;

import android.content.Context;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import de.idgard.android.R;
import de.idgard.android.addon.services.GlobalServiceRegistry;
import de.idgard.android.addon.ui.services.PreferenceService;

/**
 * 
 * @author ckaratza
 * 
 */

class PreferenceServiceImpl implements PreferenceService {

	private Context context;

	public void setContext(Context context) {
		this.context = context;
	}

	@Override
	public void saveUsername(final String username) {
		Editor editor = PreferenceManager.getDefaultSharedPreferences(context)
				.edit();
		editor.putString(PreferenceService.Preferences.LAST_USERNAME.value(),
				username);
		editor.commit();
	}

	@Override
	public String getLastSavedUsername() {
		return PreferenceManager.getDefaultSharedPreferences(context)
				.getString(PreferenceService.Preferences.LAST_USERNAME.value(),
						"");
	}

	@Override
	public void saveOpenTabUrls(final Collection<String> urls) {
		StringBuilder sb = new StringBuilder();
		for (String url : urls) {
			sb.append(url).append(
					GlobalServiceRegistry.instance().getPropertiesService()
							.getString(R.string.useragentseparator));
		}
		Editor editor = PreferenceManager.getDefaultSharedPreferences(context)
				.edit();
		editor.putString(
				PreferenceService.Preferences.PREFERENCES_TAB_HISTORY_BEFORE_ON_MODE
						.value(), sb.toString());
		editor.commit();

	}

	@Override
	public Collection<String> getSavedTabUrls() {
		String urls = PreferenceManager
				.getDefaultSharedPreferences(context)
				.getString(
						PreferenceService.Preferences.PREFERENCES_TAB_HISTORY_BEFORE_ON_MODE
								.value(), "");
		return Arrays
				.asList(urls.split(GlobalServiceRegistry.instance()
						.getPropertiesService()
						.getString(R.string.useragentseparator)));
	}

	@Override
	public void saveAddonVisibilityMode(boolean visible) {
		Editor editor = PreferenceManager.getDefaultSharedPreferences(context)
				.edit();
		editor.putBoolean(
				PreferenceService.Preferences.HIDE_IDGARD_BAR.value(), visible);
		editor.commit();

	}

	@Override
	public boolean getSavedAddonVisibilityMode() {
		return PreferenceManager.getDefaultSharedPreferences(context)
				.getBoolean(
						PreferenceService.Preferences.HIDE_IDGARD_BAR.value(),
						false);
	}

}
